import { FastifyPluginAsync } from "fastify";
import { ObjectId } from "mongodb";
import { OrderDocument } from "../../../models/schemas";
import { generateTimestampedInviteCode } from "../../../utils/inviteCode";

interface CreateOrderRequest {
  roomNumber: string;
  orderNo: string;
  messages?: string;
  parentInviteCode?: string;
  ua?: string;
  fingerprintId?: string;
  captchaId?: string;
  captchaText?: string;
}

const createOrderRoutes: FastifyPluginAsync = async (
  fastify,
  opts,
): Promise<void> => {
  fastify.post(
    "/create-order",
    {
      schema: {
        body: {
          type: "object",
          // todo
          // required: ["roomNumber", "orderNo", "captchaId", "captchaText"],
          required: ["roomNumber", "orderNo"],
          properties: {
            roomNumber: {
              type: "string",
              pattern: "^\\d{2}-\\d{2}-\\d{4}$",
            },
            orderNo: {
              type: "string",
              pattern: "^\\d+$",
              maxLength: 50,
            },
            messages: { type: "string", maxLength: 500 },
            parentInviteCode: { type: "string", maxLength: 20 },
            ua: { type: "string", maxLength: 200 },
            fingerprintId: { type: "string", maxLength: 100 },
            captchaId: { type: "string", maxLength: 100 },
            captchaText: { type: "string", maxLength: 10 },
          },
        },
        response: {
          201: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              data: {
                type: "object",
                properties: {
                  orderId: { type: "string" },
                  roomNumber: { type: "string" },
                  orderNo: { type: "string" },
                  inviteCode: { type: "string" },
                },
              },
              message: { type: "string" },
            },
          },
          400: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              error: { type: "string" },
            },
          },
          409: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              error: { type: "string" },
              message: { type: "string" },
            },
          },
          500: {
            type: "object",
            properties: {
              success: { type: "boolean" },
              error: { type: "string" },
            },
          },
        },
      },
    },
    async (request, reply) => {
      const db = fastify.mongo.db;
      if (!db) {
        return reply.code(500).send({
          success: false,
          error: "数据库连接失败",
        });
      }

      // 获取请求体数据
      const {
        roomNumber,
        orderNo,
        messages,
        parentInviteCode,
        ua,
        fingerprintId,
        captchaId,
        captchaText,
      } = request.body as CreateOrderRequest;

      try {
        // todo
        // 验证验证码
        // if (!captchaId || !captchaText) {
        //   return reply.code(400).send({
        //     success: false,
        //     error: "验证码不能为空",
        //   });
        // }

        // 获取存储的验证码
        // const storedCaptcha = fastify.captchaStore?.get(captchaId);

        // todo
        // 检查验证码是否存在和过期
        // if (!storedCaptcha || storedCaptcha.expireAt < Date.now()) {
        //   return reply.code(400).send({
        //     success: false,
        //     error: "验证码已过期或不存在",
        //   });
        // }

        // 验证码匹配
        // const isValid = storedCaptcha.text === captchaText.toLowerCase();

        // 无论验证是否成功，都删除已使用的验证码
        // fastify.captchaStore?.delete(captchaId);

        // todo
        // if (!isValid) {
        //   return reply.code(400).send({
        //     success: false,
        //     error: "验证码错误",
        //   });
        // }

        // 检查订单号是否已存在
        const existingOrder = await db
          .collection<OrderDocument>("orders")
          .findOne({ orderNo });

        if (existingOrder) {
          return reply.code(409).send({
            success: false,
            error: "订单号已存在",
            message: "该订单号已被使用，请勿重复提交",
          });
        }

        // 检查房间号是否已存在
        const existingRoomNumber = await db
          .collection<OrderDocument>("orders")
          .findOne({ roomNumber });

        // 生成唯一邀请码
        const inviteCode = existingRoomNumber
          ? existingRoomNumber.inviteCode
          : generateTimestampedInviteCode();

        // 创建新订单
        const newOrder: Omit<OrderDocument, "_id"> = {
          orderNo,
          roomNumber,
          inviteCode,
          parentInviteCode,
          status: "pending",
          messages,
          ua,
          fingerprintId,
          createdAt: Date.now(),
          updatedAt: Date.now(),
        };

        const result = await db
          .collection<OrderDocument>("orders")
          .insertOne(newOrder as any);

        // 检查邀请码是否被此房间使用过
        const existingInvitationRoomUsed = await db
          .collection<OrderDocument>("invitedRooms")
          .findOne({ roomNumber });
        if (parentInviteCode && !existingInvitationRoomUsed?.roomNumber) {
          const existingInvitationRoomUsed1 = await db
            .collection<OrderDocument>("orders")
            .findOne({ inviteCode: parentInviteCode });
          // 创建新的邀请关系记录
          await db.collection("invitedRooms").insertOne({
            roomNumber,
            invitedParentRoom: existingInvitationRoomUsed1?.roomNumber,
            createdAt: Date.now(),
          });
        }

        return reply.code(201).send({
          success: true,
          data: {
            orderId: result.insertedId.toString(),
            roomNumber,
            orderNo,
            inviteCode,
          },
          message: "订单创建成功",
        });
      } catch (error) {
        fastify.log.error(error);
        return reply.code(500).send({
          success: false,
          error: "服务器内部错误",
        });
      }
    },
  );
};

export default createOrderRoutes;
